import { Modal, Upload } from 'antd';
import ImgCrop from 'antd-img-crop';
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface';
import React, { useState } from 'react';
import 'antd/es/modal/style';
import 'antd/es/slider/style';
const App: React.FC = (props: any) => {
  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewImage, setPreviewImage] = useState('');
  const [previewTitle, setPreviewTitle] = useState('');

  const onChange: UploadProps['onChange'] = async ({ file, fileList: newFileList }) => {
    await props.setFileList(newFileList);
    props.form.setFieldValue('uploadImgs', props.fileList);
  };

  const onPreview = async (file: UploadFile) => {
    // if (!file.url && !file.preview) {
    //   file.preview = await getBase64(file.originFileObj as RcFile);
    // }
    setPreviewImage(file.response.data[0].httpurl || file.response.data[0].path);
    setPreviewOpen(true);
    setPreviewTitle(
      file.fileName ||
        file.name ||
        file.response.data[0].httpurl!.substring(
          file.response.data[0].httpurl!.lastIndexOf('/') + 1,
        ),
    );
  };
  const handleCancel = () => setPreviewOpen(false); //根据官方属性定制化裁剪框大小固定的裁剪组件属性

  return (
    <>
      <ImgCrop
        rotationSlider
        aspectSlider={true}
        quality={1}
        showReset={true}
        modalTitle="编辑图片"
        cropShape="rect"
      >
        <Upload
          name="file"
          action="/api/v1/topic/batchUpload"
          listType="picture-card"
          fileList={props.fileList}
          onChange={onChange}
          onPreview={onPreview}
          headers={{'Token':'Bearer ' + window.sessionStorage.getItem('userToken')}}
          maxCount={props.maxCount}
        >
          {props.fileList.length < 5 && '+ Upload'}
        </Upload>
      </ImgCrop>
      <Modal open={previewOpen} title={previewTitle} footer={null} onCancel={handleCancel}>
        <img alt="example" style={{ width: '100%' }} src={previewImage} />
      </Modal>
    </>
  );
};

export default App;
